var aes = require('../common/aes-cbc.js');
var app = getApp();
var baseUrl = app.data.url;
var arr = [];

//生成签名
function SetSign(array) {
  var arr = array.sort();
  var str = arr[0] + arr[1] + arr[2] + arr[3];
  return aes.AES_Encrypt(str);
}

/**
 * 生成随机数
 */
function RndNum(n) {
  var rnd = "";
  for (var i = 0; i < n; i++)
    rnd += Math.floor(Math.random() * 10);
  return rnd;
};
/* 函数描述：作为上传文件时递归上传的函数体体；
 * 参数描述： 
 * filePaths是文件路径数组
 * successUp是成功上传的个数
 * failUp是上传失败的个数
 * i是文件路径数组的指标
 * length是文件路径数组的长度
 */
function uploadDIY(url, params, filePaths, successUp, failUp, i, length, SuccessCallBack) {

  var nonce = RndNum(32);
  var timeStamp = Date.parse(new Date());
  var token = wx.getStorageSync('token');
  wx.showLoading({
    title: '上传中，请稍后...',
  })
  wx.uploadFile({
    url: baseUrl + url,
    filePath: filePaths[i],
    name: 'file',
    formData: {
      "params": aes.AES_Encrypt(JSON.stringify(params)),
      'nonce': nonce,
      'timestamp': timeStamp,
      'authInfo': token,
      'signature': SetSign([aes.AES_Encrypt(JSON.stringify(params)), nonce, timeStamp, token])
    },
    success: (res) => {
      successUp++;
      var data = JSON.parse(res.data);
      var jsonStr = aes.AES_Decrypt(data.data);
      jsonStr = jsonStr.replace(" ", "");
      if (typeof jsonStr != 'object') {
        jsonStr = jsonStr.replace(/\ufeff/g, "");
        var newData = JSON.parse(jsonStr);
        res.data = newData;
      }
      SuccessCallBack(res.data);
    },
    fail: (res) => {
      failUp++;
    },
    complete: (res) => {
      i++;
      if (i == length) {
        wx.hideLoading();
        wx.showToast({
          title: '总共' + successUp + '张上传成功,' + failUp + '张上传失败',
          icon: 'none'
        })
      } else {
        //递归调用uploadDIY函数
        uploadDIY(url, params, filePaths, successUp, failUp, i, length, SuccessCallBack);
      }
    },
  });
};

function uploadImage(url, params, SuccessCallBack) {

  wx.chooseImage({
    count: 9,
    sizeType: ['original'],
    sourceType: ['album', 'camera'],
    success: (res) => {
      var successUp = 0; //成功个数
      var failUp = 0; //失败个数
      var length = res.tempFilePaths.length; //总共个数
      var i = 0; //第几个
      uploadDIY(url, params, res.tempFilePaths, successUp, failUp, i, length, SuccessCallBack);
    },
  });
}
module.exports = {
  uploadImage: uploadImage
}